import Button from "../../ui/Button.jsx";
import {
    useDispatch,
    useSelector
} from "react-redux";
import {
    addItem,
    getCurrentQuantityById
} from "../cart/cartSlice.js";
import DeleteItem from "../cart/DeleteItem.jsx";
import UpdateItemQuantity
    from "../cart/UpdateItemQuantity.jsx";

function MenuItem({ pizza }) {
    const { id, name, unitPrice, ingredients, soldOut, imageUrl } = pizza;
    const dispatch = useDispatch();
    const currentQuantity = useSelector(getCurrentQuantityById(id));
    const isInCart = currentQuantity > 0;

    function handleAddToCart(){
        const newItem ={};
        dispatch(addItem(newItem));
    }
  return (
    <li className={"flex gap-4 py-2"}>
      <img src={imageUrl} alt={name}
        className={`h-24 ${soldOut ? 'opacity-70 grayscale' : ''}`}
      />
      <div className={"flex grow flex-col pt-0.5"}>
        <p className={"font-medium"}>{name}</p>
        <p className={"text-sm capitalize italic text-stone-500"}>{ingredients.join(', ')}</p>

          {isInCart &&
            <div className={"flex items-center gap-3 sm:gap-8"}>
                <UpdateItemQuantity pizzaId={id} currentQuantity={currentQuantity} />
                <DeleteItem pizzaId={id} />
            </div>
          }

        <div className={"mt-auto flex items-center justify-between"}>
          {!soldOut && !isInCart (
              <Button type={"small"} onClick={handleAddToCart}>
                  Add to cart
              </Button>
          )}
        </div>
      </div>
    </li>
  );
}

export default MenuItem;
